package com.itheima.core.service.product;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.core.dao.product.BrandDao;
import com.itheima.core.pojo.product.Brand;
import com.itheima.core.pojo.product.BrandQuery;

import cn.itcast.common.page.Pagination;
import redis.clients.jedis.Jedis;

@Service("brandService")
@Transactional
public class BrandServiceImpl implements BrandService{

	private static Logger logger = LoggerFactory.getLogger(BrandServiceImpl.class);
	
	@Autowired
	private BrandDao brandDao;

	@Override
	public List<Brand> selectBrandListByQuery(String name,Integer isDisplay) {
		
		BrandQuery brandQuery = new BrandQuery();
		if(name != null){
			brandQuery.setName(name);
		}
		
		if(isDisplay != null){
			brandQuery.setIsDisplay(isDisplay);
		}else{
			brandQuery.setIsDisplay(1);
		}
		return brandDao.selectBrandListByQuery(brandQuery);
	}


	@Override
	public Pagination selectPaginationByQuery(Integer pageNo,String name,Integer isDisplay) {
		BrandQuery brandQuery = new BrandQuery();
		//1.当前页
		brandQuery.setPageNo(Pagination.cpn(pageNo));
		//2.每页数
		brandQuery.setPageSize(3);
		//3.拼接参数
		StringBuilder sb = new StringBuilder();
		if(name != null){
			brandQuery.setName(name);
			sb.append("name=").append(name);
		}
		
		if(isDisplay != null){
			brandQuery.setIsDisplay(isDisplay);
			sb.append("&isDisplay=").append(isDisplay);
		}else{
			brandQuery.setIsDisplay(1);
			sb.append("&isDisplay=").append(1);
		}
		//4.设置分页对象
		Pagination pagination = new Pagination(
									brandQuery.getPageNo(), 
									brandQuery.getPageSize(), 
									brandDao.selectCount(brandQuery));
		//5.设置结果集
		pagination.setList(brandDao.selectBrandListByQuery(brandQuery));
		//url 参数
		String url = "/brand/list.do";
		pagination.pageView(url, sb.toString());
		
		return pagination;
	}


	@Override
	public Brand selectBrandById(Integer id) {
		
		Brand brand = brandDao.selectBrandById(id);
		return brand;
	}


	//保存品牌到redis
	@Autowired
	private Jedis jedis;
	@Override
	public void updateById(Brand brand) {
		brandDao.updateById(brand);
		String id = String.valueOf(brand.getId());
		Long hset = jedis.hset("brand", id, brand.getName());
		logger.info("品牌保存到redis成功！" + hset);
	}


	@Override
	public void deletes(Long[] ids) {
		brandDao.deletes(ids);
	}
	
	
	
	

	

	
}
